#include "message.hpp"
#include "net.hpp"
#include "dispatcher.hpp"
#include <iostream>

using namespace zl;

// RSP_RPC,      // RPC响应
// REQ_TOPIC,    // 主题请求

void onRpcRequest(const zl::BaseConnection::ptr &conn, zl::RpcRequest::ptr &msg)
{
    std::string body = msg->serialize();
    std::cout << body << std::endl;

    auto rpc_req = zl::MessageFactory::create<zl::RpcResponse>();
    rpc_req->setId("123");
    rpc_req->setMType(zl::MType::RSP_RPC);
    rpc_req->setRCode(zl::RCode::RECODE_OK);
    rpc_req->setresult(Json::Value("Hello, World!"));
    conn->send(rpc_req);
}

void onTopicRpcRequest(const zl::BaseConnection::ptr &conn, zl::TopicRequest::ptr &msg)
{
    std::string body = msg->serialize();
    std::cout << body << std::endl;

    auto topic_req = zl::MessageFactory::create<zl::TopicResponse>();
    topic_req->setId("333333");
    topic_req->setMType(zl::MType::RSP_TOPIC);
    topic_req->setRCode(zl::RCode::RECODE_OK);
   
    conn->send(topic_req);
}

int main()
{
    auto server = zl::ServerFactory::create(8080);

    auto dispatcherr = std::make_shared<zl::Dispatcher>();
    dispatcherr->registerHandler<zl::RpcRequest>(zl::MType::REQ_RPC, onRpcRequest);
    dispatcherr->registerHandler<zl::TopicRequest>(zl::MType::REQ_TOPIC, onTopicRpcRequest);

    auto message_cb = std::bind(&zl::Dispatcher::onMessage, dispatcherr.get(), std::placeholders::_1, std::placeholders::_2);

    server->setMessageCallback(message_cb);
    server->start();

    return 0;
}